﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using PH.Model.Schools;
using PH.Data.Schools;
using PH.Logic.Commons;
using System.Collections;
using System.Text.RegularExpressions;
using Utils;
namespace PH.Logic.Schools
{
    public class StudentLogic
    {
        public static StudentModel CreateNewStudent(StudentModel model)
        {
            return StudentCommand.CreateNewStudent(model);
        }

        public static void UpdateStudent(StudentModel model)
        {
            StudentCommand.UpdateStudent(model);
        }

        public static StudentModel GetStudent(Guid guid)
        {
            return StudentCommand.GetStudent(guid);
        }

        public static StudentCollection GetStudents(StudentQuery sea)
        {
            return StudentCommand.GetStudents(sea);
        }

        public static void DeleteStudent(Guid guid)
        {
            StudentCommand.DeleteStudent(guid);
        }
        public static int DeleteStudents(List<Guid> guids)
        {
            var i = 1;
            foreach (var g in guids)
            {
                try
                {
                    StudentCommand.DeleteStudent(g);
                    i++;
                }
                catch (Exception ex) {}
            }
            return i;
        }
        /// <summary>
        /// 导入学生资料
        /// </summary>
        /// <param name="fileGuid"></param>
        /// <param name="schoolGuid"></param>
        /// <param name="errorFileGuid"></param>
        /// <returns></returns>
        public static Guid ImportStudent(Guid fileGuid, Guid schoolGuid)
        {
            var workbook = FileLogic.GetExcel2003(fileGuid);
            Aspose.Cells.Cells cells = workbook.Worksheets[0].Cells;
            cells.DeleteBlankColumns();
            cells.DeleteBlankRows();
            var nc = 12;// cells.Columns.Count;
            cells[0, nc].PutValue("错误信息");
            
            var school = SchoolLogic.GetSchool(schoolGuid);
            if (school == null)
                throw new Utils.PhException("学校编号不正确");
            StudentCollection lst = new StudentCollection();
            var classes = ClassLogic.GetClasses(new ClassQuery() { SchoolID = school.ID });

            var i = 1;
            var rows = cells.Rows.Count - 1;
            var nowrow = 0;
            FileLogic.UpdateFile(fileGuid, 0, rows);
            while (i < cells.Rows.Count)
            {
                try
                {
                    nowrow++;
                    FileLogic.UpdateFile(fileGuid, nowrow);

                    #region 验证填写规范
                    if (cells[i, 5].Value==null || !Regex.IsMatch(cells[i, 5].Value.ToString().Trim(),@"^1|2$"))
                        throw new Utils.PhException("请填写正确的性别。");
                    #endregion

                    #region 确认班级
                    ClassModel cla = null;
                    if (cells[i, 0].Value != null)
                    {
                        var strCla = cells[i, 0].Value.ToString().Trim();
                        if (Regex.IsMatch(strCla, @"^\d{4}$"))
                        {
                            var grade = int.Parse(strCla.Substring(0, 2));
                            var cindex = int.Parse(strCla.Substring(2));
                            cla = classes.Find(p => p.GradeCode == grade && p.CIndex == cindex);
                        }else
                            throw new Utils.PhException("班级编号无效，应该是四位的数字。");
                    }else
                        throw new Utils.PhException("请输入班级编号。");
                    #endregion

                    if (cla != null)
                    {
                        var model = new StudentModel()
                        {
                            SchoolID = school.ID,
                            ClassID = cla.ID,
                            GradeCode = cla.GradeCode,
                            RealName = (string)cells[i, 4].Value,
                            StudentNo = cells[i, 8].Value != null ? cells[i, 8].Value.ToString() : "",
                            Sex = byte.Parse(cells[i, 5].Value.ToString()),
                            Address = (string)cells[i, 9].Value
                        };
                        if (cells[i, 11].Value != null)
                        {
                            model.OriSchoolCode = cells[i, 11].Value.ToString();
                            if (model.OriSchoolCode.Length < 9)
                                model.OriSchoolCode = "0" + model.OriSchoolCode;
                        }
                        if (cells[i, 10].Value != null)
                            model.Mobile = cells[i, 10].Value.ToString();
                        if (cells[i, 2].Value != null)
                            model.StudentNumber = cells[i, 2].Value.ToString();
                        if (cells[i, 3].Value != null)
                            model.NationID = Convert.ToInt32(cells[i, 3].Value);
                        else
                            throw new Utils.PhException("请填写民族代码。");

                        if (cells[i, 6].Value != null)
                        {
                            var birthday = DateTime.Now;
                            if (DateTime.TryParse(cells[i, 6].Value.ToString(), out birthday))
                                model.Birthday = birthday;
                            else
                                throw new Utils.PhException("出生日期填写错误。");
                        }
                            
                        StudentCommand.CreateNewStudent(model);
                        cells.DeleteRow(i);
                    }
                    else
                        throw new Utils.PhException("班级编号无效。");
                }
                catch (Exception ex) {
                    cells[i, nc].PutValue(ex.Message);
                    i++;
                }
            }

            if (cells.Rows.Count > 1)
            {
                var errFile = FileLogic.SaveExcel2003ToFile(workbook, "导入学生错误的记录.xls");
                return errFile.Guid;
            }
            return Guid.Empty;
        }
        /// <summary>
        /// 修改身份证号码
        /// </summary>
        /// <param name="fileGuid"></param>
        /// <param name="schoolGuid"></param>
        /// <param name="errorFileGuid"></param>
        /// <returns></returns>
        public static Guid ChangeIDNo(Guid fileGuid, Guid schoolGuid)
        {
            var workbook = FileLogic.GetExcel2003(fileGuid);
            Aspose.Cells.Cells cells = workbook.Worksheets[0].Cells;
            cells.DeleteBlankColumns();
            cells.DeleteBlankRows();
            var nc = 4;
            cells[0, nc].PutValue("错误信息");

            var school = SchoolLogic.GetSchool(schoolGuid);
            if (school == null)
                throw new Utils.PhException("学校编号不正确");
            StudentCollection lst = new StudentCollection();
            
            var i = 1;
            var rows = cells.Rows.Count - 1;
            var nowrow = 0;
            FileLogic.UpdateFile(fileGuid, 0, rows);
            while (i < cells.Rows.Count)
            {
                try
                {
                    nowrow++;
                    FileLogic.UpdateFile(fileGuid, nowrow);

                    var studentno = cells[i, 3].Value != null ? cells[i, 3].Value.ToString() : "";
                    if (!string.IsNullOrEmpty(studentno) && studentno.CheckIDNo())
                    {
                        var model = new StudentModel()
                        {
                            SchoolID = school.ID,
                            ID = int.Parse(cells[i, 0].Value.ToString()),
                            RealName = (string)cells[i, 2].Value,
                            StudentNo = studentno
                        };

                        StudentCommand.ChangeIDNO(model);
                        cells.DeleteRow(i);
                    }else
                        throw new Utils.PhException("身份证号码无效。");
                }
                catch (Exception ex)
                {
                    cells[i, nc].PutValue(ex.Message);
                    i++;
                }
            }

            if (cells.Rows.Count > 1)
            {
                var errFile = FileLogic.SaveExcel2003ToFile(workbook, "修改身份证错误的记录.xls");
                return errFile.Guid;
            }
            return Guid.Empty;
        }

        public static StudentModel GetStudent(string studentNo)
        {
            return StudentCommand.GetStudent(studentNo);
        }

        public static void RemoveStudent(Guid classGuid)
        {
            StudentCommand.RemoveStudent(classGuid);
        }
    }
}
